export default class CurveNetwork {
  constructor(curves, maxDistance) {
    this.connections = findCurveConnections(curves, maxDistance);
    this.graph = new Map();
    this.buildGraph();
  }

  buildGraph () {
    this.connections.forEach(conn => {
      this.addEdge(conn.curveA, conn.tA, conn.curveB, conn.tB);
      this.addEdge(conn.curveB, conn.tB, conn.curveA, conn.tA);
    });
  }

  addEdge (fromCurve, fromT, toCurve, toT) {
    if (!this.graph.has(fromCurve)) {
      this.graph.set(fromCurve, []);
    }
    this.graph.get(fromCurve).push({ curve: toCurve, t: toT, fromT });
  }

}
function findCurveConnections (curves, maxDistance) {
  const connections = [];
  curves.forEach((curveA, i) => {
    const samplesA = sampleCurve(curveA);
    curves.forEach((curveB, j) => {
      if (i === j) return;
      const samplesB = sampleCurve(curveB);
      samplesA.forEach((pointA, tIndexA) => {
        const tA = tIndexA / (samplesA.length - 1);
        samplesB.forEach((pointB, tIndexB) => {
          const tB = tIndexB / (samplesB.length - 1);
          if (pointA.distanceTo(pointB) < maxDistance) {
            connections.push({
              curveA, tA,
              curveB, tB
            });
          }
        });
      });
    });
  });
  return connections;
}

function sampleCurve (curve, sampleCount = 100) {
  const points = [];
  for (let t = 0; t <= 1; t += 1 / sampleCount) {
    points.push(curve.getPointAt(t));
  }
  return points;
}